//创建用户小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '../../api/user'
// 引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '../../api/user/type'
import type { UserState } from './types/types'
//引入本地存储封装
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'
// 引入路由
import { constanRoute, asyncRoutes, anyRoute } from '../../router/routes'
import router from '../../router'

function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //存储用户唯一标识token
      isLoding: false,
      menuRoutes: constanRoute, //仓库存储生成菜单需要数组（路由）
      username: null,
      avatar: '',
      asyncRoute: asyncRoutes, // 全部异步路由
      buttons: [],
    }
  },
  actions: {
    /*  用户登录 */
    async userLogin(data: loginFormData) {
      // 没有返回值的话, 默认返回一个成功Promise,undefine
      this.isLoding = true
      const result: loginResponseData = await reqLogin(data)
      // 如果登录成功, pinia存储一下token;
      if (result.code == 200) {
        //划红线: 因为对象类型没有定义
        this.token = result.data as string

        //本地存储持久化存储一份
        SET_TOKEN(result.data as string) //localStorage.setItem('TOKEN',(result.data.token as string))
        //能保证当前的async函数返回一个成功的Promise
        return 'ok'
      } else {
        this.isLoding = true
        return Promise.reject(new Error(result.message))
      }
    },
    /* 获取用户头像和昵称 */
    async userinfo() {
      //  async一定返回为Promise,如果没有指定返回值, 就默认返Promise
      const res: userInfoReponseData = await reqUserInfo()
      if (res.code == 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        this.buttons = res.data.buttons
        const userAsyncRoute = filterAsyncRoute(
          this.asyncRoute,
          res.data.routes,
        )
        this.menuRoutes = [...constanRoute, ...userAsyncRoute, anyRoute]
        const combinedRoutes = [...userAsyncRoute, anyRoute]
        // console.log('combinedRoutes',combinedRoutes);
        // 然后遍历这个新数组
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    /* 退出登录 */
    async userLogout() {
      const res = await reqLogout()
      console.log(res)
      if (res.code == 200) {
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
